package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@SuppressWarnings("all")
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    private final String PAGE_INDEX = "role/index";
    private final String PAGE_EDIT = "role/edit";
    private static final String PAGE_SUCCESS = "common/successPage";
    private final String PAGE_DELETE = "redirect:/role";
    @Reference
    private RoleService roleService;

    @RequestMapping
    public String index(Model model, @RequestParam Map<String,Object> filters) {
        //filters就是获取到的客户端的请求参数，里边可能包含:pageNum、pageSize、roleName
        //1. 判断请求参数中是否传入了pageNum和pageSize，如果没有则给其赋默认值
        if (filters.get("pageNum") == null || "".equals(filters.get("pageNum"))) {
            filters.put("pageNum",1);
        }
        if (filters.get("pageSize") == null || "".equals(filters.get("pageSize"))) {
            filters.put("pageSize",10);
        }
        PageInfo<Role> pageInfo = roleService.findPage(filters);
        model.addAttribute("page", pageInfo);
        model.addAttribute("filters", filters);
        return PAGE_INDEX;
    }

    @RequestMapping("/save")
    public String save(Role role,Model model) {
        roleService.insert(role);
        return successPage(model, "添加角色成功");
    }

    @GetMapping("/edit/{id}")
    public String edit(Model model, @PathVariable Long id) {
        Role role = roleService.getById(id);
        model.addAttribute("role", role);
        return PAGE_EDIT;
    }

    @PostMapping("/update")
    public String update(Role role, Model model) {
        roleService.update(role);
        return successPage(model, "更新角色成功");
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id){
        roleService.delete(id);
        return PAGE_DELETE;
    }
}
